package cn.xinfei.xdecision.data.core.frame.executors.collect.filter;

import cn.xinfei.xdecision.common.model.datax.consts.VariableConst;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;

import java.util.*;
import java.util.stream.Collectors;


@NoArgsConstructor
@AllArgsConstructor
public class GroovyPreVarFilter implements VarFilter<String> {

    private Map<String, Set<String>> deriveVarAndParamMap;
    private Map<String, Integer> varCodeAndTypeMap;

    @Override
    public Set<String> actionVar(Set<String> varCodes) {

        Set<String> actionVarList = new HashSet<>();
        if (CollectionUtils.isEmpty(varCodes)) {
            return actionVarList;
        }

        if (MapUtils.isNotEmpty(deriveVarAndParamMap)) {
            Map<String, Set<String>> groovyPreVarAndParams = deriveVarAndParamMap.entrySet().stream()
                    .filter(var -> {
                        Optional<String> firstParamVar = Optional.ofNullable(var.getValue())
                                .orElse(Collections.emptySet()).stream()
                                .filter(paramVar -> VariableConst.GROOVY_AFTER_VAR_ENUMS.contains(String.valueOf(varCodeAndTypeMap.get(paramVar)))).findFirst();
                        return !firstParamVar.isPresent();
                    })
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

            if (MapUtils.isNotEmpty(groovyPreVarAndParams)) {
                actionVarList = varCodes.stream().filter(groovyPreVarAndParams::containsKey)
                        .collect(Collectors.toSet());
            }
        }
        return actionVarList;
    }
}
